package com.general.campus.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: RouterServlet
 * @author: general
 * @version: 1.0
 * @create: 2021-06-12 20:22
 **/
public class RouterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = new String(request.getRequestURI());
        String relativePath = requestURI.replace(request.getContextPath(), "");
        if(relativePath.endsWith(".servlet") || relativePath.contains("servlet")){
            RequestDispatcher rd = request.getRequestDispatcher("/servlet");
            request.setAttribute("realContextPath", requestURI);
            rd.forward(request, response);
        }
        else if(relativePath.endsWith(".jsp") || relativePath.contains("jsp")){
            this.doGet(request, response);
        }
        else{
            PrintWriter writer = response.getWriter();
            writer.write(String.format("Sorry, context path [%s] cannot forward! ", request.getRequestURI()));
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}
